package com.jcp.baselibrary.base;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;

import java.util.Stack;

/**
 * =========================================================
 * @ProjectName:
 * @ClassName: APPActivityManager
 * @Description: activity堆栈式管理
 * @Author: jincp
 * @CreateDate: 2019/3/14 20:06
 * =========================================================
 */
public class APPActivityManager implements Application.ActivityLifecycleCallbacks {

    private static final APPActivityManager instance = new APPActivityManager();
    private Stack<Activity> activities = new Stack();


    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        this.activities.push(activity);

    }

    @Override
    public void onActivityStarted(Activity activity) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        this.activities.remove(activity);
    }

    @Override
    public void onActivityResumed(Activity activity) {
        this.activities.remove(activity);
        this.activities.push(activity);
    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    public <T extends Activity> T getTopActivity() {
        return this.activities.isEmpty() ? null : (T) this.activities.peek();
    }

    public void finish(Class<? extends Activity> targetActivity) {
        try {
            for (Activity activity : activities) {
                if (activity.getClass().equals(targetActivity)) {
                    activity.finish();
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void finishAll() {
        try {
            for (Activity activity : activities) {
                activity.finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        activities.clear();
    }

    private APPActivityManager() {
    }

    public static APPActivityManager getInstance() {
        return instance;
    }


}
